package com.lmc.gateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomConfig> implements Ordered {
    public CustomGatewayFilterFactory() {
        super(CustomConfig.class);
    }

    @Override
    public GatewayFilter apply(CustomConfig config) {
        return new GatewayFilter() {
            /**
             * 过滤器逻辑
             *ServerWebExchange 是网关的请求对象,提供了对http请求和响应的访问
             *GatewayFilterChain 是过滤器链对象，可以调用chain.filter()方法来执行下一个过滤器
             * Mono Reactor的核心类，数据流发布者，Mono最多只能触发一个事件，可以把它用在异步任务完成时发出通知
             *Mono.fromRunnable 创建一个包含Runable元素的数据流
             * @return
             */
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //pre类型  执行请求  post类型
                log.info("pre fillter , config"+ config); //pre类型过滤器代码逻辑
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    log.info("post filter ..."); //post类型过滤器代码逻辑
                }));
            }
        };
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
